package at.fhv.components.or;

import java.awt.image.renderable.ParameterBlock;
import java.util.HashMap;
import java.util.Map;

import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;

import at.fhv.framework.CommonImageProcessingHelper;
import at.fhv.framework.events.ImageEvent;
import at.fhv.framework.listeners.ImageProcessingListener;
import at.fhv.framework.listeners.RefireListener;

/**
 * The AndFilter class.
 * 
 * @author Michael Sieber
 */
public class OrFilter implements ImageProcessingListener, RefireListener
{
	private Map<Object, PlanarImage>	_images;
	private CommonImageProcessingHelper	_helper;

	public OrFilter()
	{
		_helper = new CommonImageProcessingHelper(this);
		_images = new HashMap<Object, PlanarImage>();
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void refire() {
		execute();
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void imageChanged(ImageEvent event) {
		_images.put(event.getSource(), event.getImage());
		execute();
	}

	private void execute() {
		if (_images.size() > 1)
		{
			ParameterBlock pb = new ParameterBlock();
			for (PlanarImage img : _images.values())
			{
				pb.addSource(img);
			}

			// AND the two images together.
			PlanarImage img = JAI.create("or", pb);
			_helper.fireImageProcessingEvent(new ImageEvent(this, img));
		}
		else if (_images.size() == 1)
		{ /*
		 * if only one image is available fire it
		 */
			_helper.fireImageProcessingEvent(new ImageEvent(this, _images.values().iterator()
					.next()));
		}
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void addRefireListener(RefireListener listener) {
		_helper.addRefireListener(listener);
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void removeRefireListener(RefireListener listener) {
		_helper.removeRefireListener(listener);
	}

	/**
	 * Add an image change listener
	 * 
	 * @param listener
	 *            The image change listener to add
	 */
	public void addImageChangeListener(ImageProcessingListener listener) {
		_helper.addImageProcessingListener(listener);

		// force all previous beans to refire their event
		_helper.fireRefireEvent();
	}

	/**
	 * Remove an image change listener
	 * 
	 * @param listener
	 *            The image change listener to remove
	 */
	public void removeImageChangeListener(ImageProcessingListener listener) {
		_helper.removeImageProcessingListener(listener);
	}
}
